import React, { useState, useEffect } from 'react';
import { Button, Spin, Alert, Table } from 'dingtalk-design-desktop';

// 定义字典项接口
interface DictItem {
  id: string;
  name: string;
  code: string;
  [key: string]: any; // 其他可能的字段
}

// 定义响应数据接口
interface DictResponse {
  data: DictItem[];
  total: number;
  success: boolean;
  message?: string;
}

const FetchExample3: React.FC = () => {
  const [loading, setLoading] = useState<boolean>(false);
  const [error, setError] = useState<string | null>(null);
  const [dictData, setDictData] = useState<DictItem[]>([]);
  const [total, setTotal] = useState<number>(0);

  // 发送POST请求获取字典数据
  const fetchDictData = async () => {
    setLoading(true);
    setError(null);
    
    try {
      // 请求参数
      const requestBody = {
        cCodeName: 'net_order.category',
        parentId: '-1',
        cName: '',
        pageIndex: 0,
        pageSize: 10,
        sortField: '',
        sortOrder: ''
      };

      // 设置请求选项
      const requestOptions: RequestInit = {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json;charset=UTF-8',
        },
        credentials: 'include', // 包含跨域请求的cookie
        body: JSON.stringify(requestBody)
      };

      // 发送POST请求
      const response = await fetch(
        'https://szsq.3cerp.com/pages/sys/getBasDict.htm',
        requestOptions
      );
      
      // 检查响应是否成功
      if (!response.ok) {
        throw new Error(`HTTP error! Status: ${response.status}`);
      }
      
      // 解析 JSON 数据
      const result: DictResponse = await response.json();
      
      if (result.success) {
        setDictData(result.data || []);
        setTotal(result.total || 0);
      } else {
        throw new Error(result.message || '请求失败');
      }
    } catch (err) {
      // 处理错误
      setError(err instanceof Error ? err.message : 'An unknown error occurred');
      console.error('获取字典数据错误:', err);
    } finally {
      setLoading(false);
    }
  };

  // 组件挂载时获取数据
  useEffect(() => {
    fetchDictData();
  }, []);

  // 刷新数据
  const handleRefresh = () => {
    fetchDictData();
  };

  // 定义表格列
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '编码',
      dataIndex: 'code',
      key: 'code',
    }
  ];

  return (
    <div style={{ padding: '20px' }}>
      <h2>指定POST请求示例</h2>
      <p>请求地址: https://szsq.3cerp.com/pages/sys/getBasDict.htm</p>
      
      <div style={{ marginBottom: '16px' }}>
        <Button 
          type="primary" 
          onClick={handleRefresh}
          loading={loading}
          disabled={loading}
        >
          {loading ? '获取中...' : '刷新数据'}
        </Button>
      </div>
      
      {/* 错误提示 */}
      {error && (
        <Alert 
          type="error" 
          message="错误" 
          description={error} 
          closable 
          onClose={() => setError(null)} 
          style={{ marginBottom: '16px' }}
        />
      )}
      
      {/* 数据展示 */}
      {!error && (
        <div>
          <div style={{ marginBottom: '16px' }}>
            <span>总共 {total} 条数据</span>
          </div>
          
          {loading ? (
            <div style={{ textAlign: 'center', padding: '40px' }}>
              <Spin size="large" />
              <p>正在获取数据...</p>
            </div>
          ) : dictData.length > 0 ? (
            <Table 
              dataSource={dictData} 
              columns={columns} 
              pagination={false}
              rowKey="id"
            />
          ) : (
            <p>暂无数据</p>
          )}
        </div>
      )}
      
      <div style={{ marginTop: '24px', padding: '16px', backgroundColor: '#f5f5f5', borderRadius: '4px' }}>
        <h3>请求详情:</h3>
        <ul>
          <li><strong>URL:</strong> https://szsq.3cerp.com/pages/sys/getBasDict.htm</li>
          <li><strong>Method:</strong> POST</li>
          <li><strong>Content-Type:</strong> application/json;charset=UTF-8</li>
          <li><strong>Credentials:</strong> include (包含cookie)</li>
        </ul>
        <h3>请求参数:</h3>
        <pre>{`{
  cCodeName: "net_order.category",
  parentId: "-1",
  cName: "",
  pageIndex: 0,
  pageSize: 10,
  sortField: "",
  sortOrder: ""
}`}</pre>
      </div>
    </div>
  );
};

export default FetchExample3;